// pages/mine/index/index.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.command

Page({

    /**
     * 页面的初始数据
     */
    data: {
        loginOk: false,
        dataLength: 0,
        foldersLength: 0,
    },

    addPic1: function (e) {
        if(!app.globalData.loginOk){
            wx.showToast({
              title: '请您先登录',
              icon: 'none'
            })
            return
        }
        var that = this;
        var n = 0;
        wx.chooseImage({
          count: n, // 默认9，设置图片张数
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            // console.log(res.tempFilePaths)
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            var tempFilePaths = res.tempFilePaths
            that.setData({
                tempFilePaths: tempFilePaths
            });
            that.fb()
          }
        })
      },
    
      //发布按钮
      fb() {
        let imgbox = this.data.tempFilePaths[0]
        if (!imgbox || imgbox.length < 1) {
          wx.showToast({
            icon: "none",
            title: '请选择图片'
          })
          return
        }
        wx.showLoading({
          title: '发布中...',
        })
          let promiseArr = [];
            promiseArr.push(new Promise((reslove, reject) => {
              let item = this.data.tempFilePaths[0];
              let suffix = /\.\w+$/.exec(item)[0]; //正则表达式返回文件的扩展名
              wx.cloud.uploadFile({
                cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
                filePath: item, // 小程序临时文件路径
              }).then(res => {
                console.log("上传结果", res.fileID)
                this.setData({
                  fileIDs: res.fileID
                })
                reslove()
              }).catch(error=>{
                console.log("上传失败",error);
              })
            }))
          
          Promise.all(promiseArr).then(res => {
            let that = this
            wx.cloud.database().collection('anmimg').add({
              data: {
                fileIDs: this.data.fileIDs,
              },
              success: res => {
                wx.cloud.callFunction({
                    name: 'getUserImages', 
                    data: {
                        '_openid': app.globalData.openId, 
                    },
                    success: res => {
                        console.log(res.result)
                        that.setData({
                            dataList:res.result.data,
                            dataLength:res.result.data.length
                        })
                        app.globalData.dataList = res.result.data
                        app.globalData.dataLength = res.result.data.length
                        wx.hideLoading()
                        wx.showToast({
                            title: '发布成功',
                        })
                        console.log('发布成功', res)
                    },
                })
                
              },
              fail: err => {
                wx.hideLoading()
                wx.showToast({
                  icon: 'none',
                  title: '网络不给力....'
                })
                console.error('发布失败', err)
              }
              
            })
          })
          Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
            console.log("图片上传完成后再执行")
          })
      },

    loadByWechat(){
        let that = this
        wx.getUserProfile({
        desc: '用户完善会员资料',
        })
      
        .then(resf=>{
            wx.showLoading({
              })
            wx.cloud.callFunction({
                name: 'getUserImages', 
                data: {
                    '_openid': app.globalData.openId, 
                },
                success: res => {
                    console.log(res.result)
                    that.setData({
                        dataList:res.result.data,
                        dataLength:res.result.data.length
                    })
                    app.globalData.dataList = res.result.data
                    app.globalData.dataLength = res.result.data.length
                    wx.cloud.callFunction({
                        name: 'getFolders',
                        data: {
                            '_openid': app.globalData.openId
                        },
                        success: resp => {
                            console.log(resp.result)
                            that.setData({
                                foldersList:resp.result.data,
                                foldersLength:resp.result.data.length
                            })
                            app.globalData.foldersList = resp.result.data
                            app.globalData.foldersLength = resp.result.data.length
                            app.globalData.userInfo = resf.userInfo
                            wx.reLaunch({
                                url: '/pages/mine/index/index?nickName='+resf.userInfo.nickName+'&avatarUrl='+resf.userInfo.avatarUrl+
                                '&dataLength='+app.globalData.dataLength+'&foldersLength='+app.globalData.foldersLength,
                            })
                            wx.hideLoading({
                              })
                        },fail: resp =>{
                            console.log("asd")
                            console.log(resp)
                            wx.hideLoading({
                            })
                        }
                    })
                   
                },
            })
            app.globalData.loginOk = true 
            app.globalData.userInfo = resf.userInfo
            wx.setStorageSync('loginOk', true)
            wx.setStorageSync('userInfo', resf.userInfo)
        })
        .catch(err=>{
          console.log("用户拒绝了微信授权登录",err);
       })
     },
    
    exit(){
        wx.showModal({
            content:"确定退出吗"
        }).then(res=>{
            if(res.confirm){
                app.globalData.loginOk = false
                this.setData({
                    loginOk:false
                })
            wx.setStorageSync('userInfo', null)
            }
        })
    },
    touchmove(){},
    toAdd(){
        if(!app.globalData.loginOk){
            wx.showToast({
              title: '请您先登录',
              icon: 'none'
            })
            return
        }
        wx.navigateTo({
          url: '../../share/myshare/index',
        })
    },

    toStorage(){
        if(!app.globalData.loginOk){
            wx.showToast({
              title: '请您先登录',
              icon: 'none'
            })
            return
        }
        wx.navigateTo({
          url: '../storage/index',
        })
    },

    toShangchuan(){
        wx.navigateTo({
          url: '../shangchuan/index',
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            loginOk:app.globalData.loginOk,
            nickName:app.globalData.userInfo.nickName,
            avatarUrl:app.globalData.userInfo.avatarUrl,
            dataLength:app.globalData.dataLength,
            foldersLength:app.globalData.foldersLength,
        })
    },

   
})